#include<stdio.h>
#include<stdlib.h>
#include <stdarg.h>
#include<ctype.h>
#include"string.h"

#include"headfile.h"
#include"uprintf.h"

char print_buffer[PRINT_BUFFER_SIZE];
void uprintf(char *fmt, ...) {
    int size;
    va_list arg_ptr;
    va_start(arg_ptr, fmt);
    size = vsprintf(print_buffer, fmt, arg_ptr);
    va_end(arg_ptr);
		uart_putbuff(PRINTF_UART,print_buffer,size);
}

static char s[22] = {'b', 'y', 16, 6};
void send_wave(float a1, float a2, float a3, float a4) {
  float dat[4];
  dat[0]=BS_transform(a1);
  dat[1]=BS_transform(a2);
  dat[2]=BS_transform(a3);
  dat[3]=BS_transform(a4);
  s[20] = '\r';
  s[21] = '\n';
  memcpy(s + 4, dat, sizeof(float));
  memcpy(s + 8, dat+1, sizeof(float));
  memcpy(s + 12,dat+2, sizeof(float));
  memcpy(s + 16,dat+3, sizeof(float));
  uart_putbuff(PRINTF_UART,s,22);
}

int a2i(char *string){
  int val,flag;
  unsigned int cutlim,cutoff;

  if(string==NULL) return 0;
  while(*string == ' '||*string == '\t')
    string ++;

  if(*string =='-'){
    flag = 1;
    string++;
  }
  else{
    flag = 0;
    if(*string == '+')
        string ++;
  } 

  cutoff = flag ?(unsigned int) INT_MAX+1 : INT_MAX;
  cutlim = cutoff % 10;
  cutoff /= 10;                        //用来判断是否会超出整数范围的指标

  for(val = 0;isdigit(*string);string++){
    if(val >cutoff ||(val==cutoff && (*string - '0')>cutlim))  //满足这个条件 表示转换的数会超出整数范围i 返回相应的上界或者下界
            return flag ? INT_MIN : INT_MAX;
    val = val*10 + (*string - '0');
  }

  if(flag)
    return val*(-1);
  else
    return val;
}

float a2f(char *string){
  float val,power;
  int flag,exp;

  if(string == NULL) return 0;
  for(; isspace(*string);string++);

  flag = (*string == '-') ? -1 : 1;
  if(*string == '-' || *string =='+')
  string++;

  for(val = 0.0;isdigit(*string);string++){
    val = val*10.0 + (*string - '0');
  }

  if(*string == '.')  //对小数点后面部分数的处理
    string++;
  for(power = 1.0;isdigit(*string);string++){
    val = val*10.0 + (*string - '0');
    power *= 10.0;
  }
  val = (flag * val) / power;

  if(*string == 'e'|| *string == 'E'){     //对含有科学计数法的 字符的处理
    flag = (*++string == '-') ? -1 : 1;
    if (*string =='+' ||*string == '-')
      string++;
    for(exp = 0;isdigit(*string);string++)
      exp = exp*10 + (*string - '0');
    if(flag == -1){
      while(exp-- >0)
              val /= 10.0;
    }
    if(flag == 1){
      while(exp-- >0)
              val *= 10.0;
    }
  }
  return val;
}


float BS_transform(float fValue){
  vofa_wave	d1, d2; 
  d1.fl = fValue;
  d2.ch[0] = d1.ch[3];
  d2.ch[1] = d1.ch[2];
  d2.ch[2] = d1.ch[1];
  d2.ch[3] = d1.ch[0]; 
  return d2.fl;
}

void vofa_sendwave(float a1,float a2,float a3,float a4){
  float vofa_data[4];
  char tail[4] = {0x00, 0x00, 0x80, 0x7f};

  vofa_data[0]=BS_transform(a1);
  vofa_data[1]=BS_transform(a2);
  vofa_data[2]=BS_transform(a3);
  vofa_data[3]=BS_transform(a4);
  
  uart_putbuff(PRINTF_UART,(uint8 *)vofa_data,(uint16)16);
  uart_putbuff(PRINTF_UART,tail,(uint16)4);
}